package com.jinsp.skinlib;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.support.annotation.IdRes;
import android.support.annotation.StringDef;
import android.support.v4.content.res.ResourcesCompat;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * Created by luoshuai on 12/20/21
 * <p>
 * 字体工具类
 */
public class FontUtils {

    private static final String ASSETS_FONT_FOLDER = "fonts";   //Assets文件夹下字体目录

    public static final String DEFAULT_FONT_SERIF = "SERIF";
    public static final String DEFAULT_FONT_MONOSPACE = "MONOSPACE";
    public static final String DEFAULT_FONT_SANS_SERIF = "SANS_SERIF";

    @StringDef({DEFAULT_FONT_SERIF, DEFAULT_FONT_MONOSPACE, DEFAULT_FONT_SANS_SERIF})
    @Retention(RetentionPolicy.CLASS)
    @Target(ElementType.PARAMETER)
    public @interface DefaultFontName {
    }

    /**
     * 获取Assets文件夹下的字体，字体文件越大越耗时
     *
     * @param assetManager assets文件夹
     * @return 是否存在字体(.ttf)
     */
    public static Typeface getTypefaceFromAssets(AssetManager assetManager, String fontName) {
        if (assetManager == null) {
            return null;
        }
        try {
            long start = System.currentTimeMillis();
            String[] assetsFilePath = assetManager.list(ASSETS_FONT_FOLDER);
            if (assetsFilePath != null && assetsFilePath.length > 0) {
                for (String filePath : assetsFilePath) {
                    if (TextUtils.isEmpty(fontName)) {
                        //寻找第一个字体
                        if (filePath.endsWith(".ttf")) {
                            Typeface typeface = Typeface.createFromAsset(assetManager, ASSETS_FONT_FOLDER
                                    + File.separator + filePath);
                            Log.d(FontUtils.class.getCanonicalName(), "加载字体文件" + filePath +
                                    "耗时：" + (System.currentTimeMillis() - start) + "ms");
                            return typeface;
                        }
                    } else {
                        if (TextUtils.equals(fontName, filePath)) {
                            Typeface typeface = Typeface.createFromAsset(assetManager, ASSETS_FONT_FOLDER
                                    + File.separator + filePath);
                            Log.d(FontUtils.class.getCanonicalName(), "加载字体文件" + filePath +
                                    "耗时：" + (System.currentTimeMillis() - start) + "ms");
                            return typeface;
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressLint("ResourceType")
    public static Typeface getTypefaceFromFont(Context context, @IdRes int fontId) {
        return ResourcesCompat.getFont(context, fontId);
    }

    /**
     * 通过反射替换全局字体，APP主题内部需要设置<item name="android:typeface">DefaultFontName</item>
     *
     * @param defaultFontName 当前系统设置的字体
     * @param newTypeface     新字体
     */
    public static void changeDefaultFont(@DefaultFontName String defaultFontName, Typeface newTypeface) {
        if (TextUtils.isEmpty(defaultFontName) || newTypeface == null) {
            return;
        }
        try {
            Field declaredField = Typeface.class.getDeclaredField(defaultFontName);
            if (declaredField != null) {
                declaredField.setAccessible(true);
                //替换新字体
                declaredField.set(null, newTypeface);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
